<template>
  <div class="app">
    <a-breadcrumb style="margin-bottom: 10px">
      <a-breadcrumb-item>重点人群信息/重点人群信息</a-breadcrumb-item>
    </a-breadcrumb>
    <a-row class="pd20 mt20">
      <a-col :span="6">
        人口姓名：
        <a-input placeholder="请输入" v-model="queryForm.name" />
      </a-col>
      <a-col :span="6">
        联系方式：
        <a-input placeholder="请输入" v-model="queryForm.phone" />
      </a-col>
      <a-col :span="6">
        人员类型：
        <a-select v-model="queryForm.humanKeyPointId" placeholder="请选择">
          <a-select-option
            v-for="item in classList"
            :key="item.id"
            :value="item.id"
            filterable
            allowClear
          >
            {{ item.humanKeyPointClassName }}
          </a-select-option>
        </a-select>
      </a-col>
      <a-col :span="6">
        性别：
        <a-select v-model="queryForm.gender" placeholder="请选择">
          <a-select-option
            v-for="item in genderList"
            :key="item.id"
            :value="item.id"
          >
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-col>
      <a-col :span="6">
        身份证号码：
        <a-input placeholder="请输入" v-model="queryForm.idCardNumber" />
      </a-col>
      <a-col :span="6">
        监护人姓名：
        <a-input placeholder="请输入" v-model="queryForm.guardianName" />
      </a-col>
      <!-- <a-col :span="6">
        监护人手机号：
        <a-input placeholder="请输入"
                 v-model="queryForm.guardianPhone" />
      </a-col> -->
      <a-col :span="8">
        创建时间范围：
        <a-range-picker
          style="width: 350px"
          @change="onChange"
          v-model="dateRange"
          :placeholder="['开始日期', '结束日期']"
        />
      </a-col>
      <a-col :span="4">
        <a-button type="primary" @click="getList"> 查询 </a-button>&emsp;&nbsp;
        <a-button @click="cleanQuery">重置</a-button>
      </a-col>
    </a-row>
    <a-row class="pd20 mt20">
      <div class="btn_box">
        <div>重点人群信息</div>
        <a-button
          type="primary"
          @click="addFn"
          v-hasPermi="['zhonghe:zdrqxx:add']"
          >添加</a-button
        >
      </div>
      <a-spin :spinning="loading">
        <a-table
          :scroll="{ x: 500 }"
          :columns="columns"
          :data-source="tableData"
          :pagination="false"
        >
          <template slot="idCardNumber" slot-scope="text, record">
            <div class="phone-cell">
              <span>{{
                record.showIdCardNumber ? text : $maskChineseIdCard(text)
              }}</span>
              <a-icon
                :type="record.showIdCardNumber ? 'eye-invisible' : 'eye'"
                @click.stop="toggleIdNumberVisibility2(record)"
              />
            </div>
          </template>
          <template slot="phone" slot-scope="text, record">
            <div class="phone-cell">
              <span>{{
                record.showPhone ? text : $desensitizePhone(text)
              }}</span>
              <a-icon
                :type="record.showPhone ? 'eye-invisible' : 'eye'"
                @click.stop="togglePhoneVisibility(record)"
              />
            </div>
          </template>
          <template slot="headImageUrl" slot-scope="text">
            <img :src="text" style="width: 50px; height: 50px" />
          </template>
          <span slot="action" slot-scope="text, record">
            <a
              @click="editFn(text, 'view')"
              v-hasPermi="['zhonghe:zdrqlxgl:edit']"
              >查看</a
            >
            <a-divider type="vertical" />
            <a
              @click="editFn(text, 'edit')"
              v-hasPermi="['zhonghe:zdrqxx:edit']"
              >修改</a
            >
            <a-divider type="vertical" />
            <a
              @click="delFn(text, record)"
              v-hasPermi="['zhonghe:zdrqxx:del']"
              class="red"
              >删除</a
            >
          </span>
        </a-table>
        <div class="page_box">
          <a-pagination
            v-model="queryForm.offset"
            :page-size-options="['20', '30', '40', '50']"
            :total="total"
            show-size-changer
            :page-size="queryForm.current"
            @showSizeChange="onShowSizeChange"
            @change="pageChange"
            :show-total="(total) => `共 ${total} 条`"
          ></a-pagination>
        </div>
      </a-spin>
    </a-row>
    <a-modal
      title="重点人群信息配置"
      :visible="dialogVisible"
      width="38%"
      ok-text="确认"
      cancel-text="取消"
      @cancel="dialogVisible = false"
      @ok="putDict"
    >
      <a-form :form="form">
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="头像"
        >
          <Upload :imageUrl="img" :limit="1" @getImg="getImg"></Upload>
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="姓名"
        >
          <a-input
            :disabled="ModalType == 'view'"
            v-decorator="[
              'name',
              { rules: [{ required: true, message: '请输入姓名' }] },
            ]"
            placeholder="请输入姓名"
          />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="性别"
        >
          <a-select
            :disabled="ModalType == 'view'"
            v-decorator="[
              'gender',
              { rules: [{ required: true, message: '请选择性别' }] },
            ]"
            placeholder="请选择性别"
            allowClear
          >
            <a-select-option
              v-for="(item, index) in genderList"
              :key="index"
              :value="item.id"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="人员类型"
        >
          <a-select
            :disabled="ModalType == 'view'"
            v-decorator="[
              'humanKeyPointId',
              { rules: [{ required: true, message: '请选择人员类型' }] },
            ]"
            placeholder="请选择人员类型"
            allowClear
          >
            <a-select-option
              v-for="(item, index) in classList"
              :key="index"
              :value="item.id"
            >
              {{ item.humanKeyPointClassName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="身份证号码"
        >
          <a-input
            :disabled="ModalType == 'view'"
            v-decorator="[
              'idCardNumber',
              { rules: [{ required: true, message: '请输入身份证号码' }] },
            ]"
            placeholder="请输入身份证号码"
            :maxlength="18"
          />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="年龄"
        >
          <a-input disabled v-decorator="['age']" />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="联系方式"
        >
          <a-input
            :disabled="ModalType == 'view'"
            v-decorator="[
              'phone',
              { rules: [{ required: true, message: '请输入联系方式' }] },
            ]"
            placeholder="请输入联系方式"
          />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="常住地址"
        >
          <a-input
            :disabled="ModalType == 'view'"
            v-decorator="[
              'addr',
              { rules: [{ required: true, message: '请输入常住地址' }] },
            ]"
            placeholder="请输入常住地址"
          />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="监护人姓名"
        >
          <a-input
            :disabled="ModalType == 'view'"
            v-decorator="[
              'guardianName',
              { rules: [{ required: true, message: '请输入监护人姓名' }] },
            ]"
            placeholder="请输入监护人姓名"
          />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="监护人关系"
        >
          <a-input
            :disabled="ModalType == 'view'"
            v-decorator="[
              'guardianRelation',
              { rules: [{ required: true, message: '请输入监护人关系' }] },
            ]"
            placeholder="请输入监护人关系"
          />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="监护人联系方式"
        >
          <a-input
            :disabled="ModalType == 'view'"
            v-decorator="[
              'guardianPhone',
              { rules: [{ required: true, message: '请输入监护人联系方式' }] },
            ]"
            placeholder="请输入监护人联系方式"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { Modal } from "ant-design-vue";
import { message } from "ant-design-vue";
import Upload from "@/component/upload/index.vue";
import dayjs from "dayjs";
export default {
  components: {
    Upload,
  },
  data() {
    return {
      humanTypeList: [],
      dateRange: [],
      loading: true,
      dialogVisible: false,
      queryForm: { current: 20, offset: 1 },
      total: 0,
      form: this.$form.createForm(this, { name: "coordinated" }),
      id: null,
      tableData: [],
      img: "",
      columns: [
        { title: "序号", dataIndex: "index", key: "index" },
        {
          title: "人口ID",
          dataIndex: "id",
          key: "id",
        },
        {
          title: "姓名",
          dataIndex: "name",
          key: "name",
        },
        {
          title: "照片",
          dataIndex: "headImageUrl",
          key: "headImageUrl",
          scopedSlots: { customRender: "headImageUrl" },
        },
        {
          title: "性别",
          dataIndex: "genderName",
          key: "genderName",
        },
        {
          title: "人员类型",
          dataIndex: "humanKeyPointId",
          key: "humanKeyPointId",
          customRender: (text) => {
            let findOne = this.classList.find((item) => item.id == text);
            return findOne ? findOne.humanKeyPointClassName : "无";
          },
        },
        {
          title: "身份证号码",
          dataIndex: "idCardNumber",
          key: "idCardNumber",
          scopedSlots: { customRender: "idCardNumber" },
          width: 170,
        },
        {
          title: "年龄",
          dataIndex: "age",
          key: "age",
          customRender: (text, record) => {
            return this.getAge(record.idCardNumber);
          },
        },
        {
          title: "联系方式",
          dataIndex: "phone",
          key: "phone",
          scopedSlots: { customRender: "phone" },
          width: 150,
        },
        {
          title: "常住地址",
          dataIndex: "addr",
          key: "addr",
        },
        {
          title: "监护人姓名",
          dataIndex: "guardianName",
          key: "guardianName",
        },
        {
          title: "监护人关系",
          dataIndex: "guardianRelation",
          key: "guardianRelation",
        },
        {
          title: "监护人联系方式",
          dataIndex: "guardianPhone",
          key: "guardianPhone",
        },
        {
          title: "最近更新时间",
          dataIndex: "updateTime",
          key: "updateTime",
        },
        {
          title: "创建时间",
          dataIndex: "createTime",
          key: "createTime",
        },
        {
          title: "操作",
          key: "action",
          width: 150,
          scopedSlots: { customRender: "action" },
        },
      ],
      formItemLayout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 19 },
      },
      formTailLayout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 19, offset: 4 },
      },
      genderList: [
        { id: 0, label: "女" },
        { id: 1, label: "男" },
      ],
      classList: [],
      ModalType: "",
    };
  },
  async mounted() {
    await this.getTypetList();
    await this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      const url = "/government-platform-center/humanKeyPoint";
      const params = this.queryForm;
      this.$axios
        .get(url, {
          params: params,
        })
        .then((res) => {
          if (res.data.code == 0) {
            this.tableData = res.data.data.map((item, index) => {
              item["showPhone"] = false;
              item["index"] = index + 1;
              if ((item.gender = 1)) {
                item["genderName"] = "男";
              } else if ((item.gender = 0)) {
                item["genderName"] = "女";
              }
              item["age"] = this.getAge(item.idCardNumber);
              this.classList.forEach((i) => {
                if (i.id == item.humanKeyPointId) {
                  item["humanKeyPointClassName"] = i.humanKeyPointClassName;
                }
              });
              return item;
            });
            this.total = res.data.total;
            this.loading = false;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    getTypetList() {
      this.loading = true;
      const url = "/government-platform-center/humanKeyPointClass";
      const params = {
        current: 999999,
        offset: 1,
      };
      this.$axios
        .get(url, {
          params: params,
        })
        .then((res) => {
          if (res.data.code == 0) {
            this.classList = res.data.data;
          }
        });
    },
    getAge(str) {
      if (str && str.length > 10) {
        // 提取年份
        const year = str.substring(6, 10); // 从第6位到第10位提取年份
        const currentYear = new Date().getFullYear(); // 获取当前年份

        // 计算年龄
        const age = currentYear - parseInt(year, 10);
        return age;
      }
    },
    cleanQuery() {
      this.queryForm = { current: 20, offset: 1 };
      this.dateRange = [];
      this.getList();
    },
    //
    getImg(e) {
      this.img = e;
    },
    // 分页
    onShowSizeChange(current, pageSize) {
      this.queryForm.current = pageSize;
      this.getList();
    },
    pageChange(current) {
      this.queryForm.offset = current;
      this.getList();
    },
    delFn(text, record) {
      const that = this;
      Modal.confirm({
        title: "确认删除",
        content: "您确定要删除这项内容吗？",
        okText: "确认",
        cancelText: "取消",
        onOk() {
          const url = `/government-platform-center/humanKeyPoint/deleteById`;
          const form = { id: text.id };
          that.$axios
            .post(url, form, {
              headers: {
                "Content-Type": "application/x-www-form-urlencoded",
              },
            })
            .then((res) => {
              if (res.data.code == 0) {
                that.getList();
                message.success("操作成功");
              }
            });
        },
        onCancel() {
          // 在此处理取消逻辑
          console.log("删除已取消");
        },
      });
    },
    goData(text, record) {
      this.$router.push({
        path: "/dataDict",
        query: { dictType: text.dictType, id: text.id },
      });
    },
    addFn() {
      this.dialogVisible = true;
      this.id = null;
      this.ModalType = "add";
      this.form.resetFields();
    },
    editFn(text, type) {
      this.ModalType = type;
      this.dialogVisible = true;
      const url = `/government-platform-center/humanKeyPoint/${text.id}`;
      const params = this.queryForm;
      this.$axios
        .get(url, {
          params: params,
        })
        .then((res) => {
          if (res.data.code == 0) {
            const data = res.data.data;
            data.age = this.getAge(data.idCardNumber);
            this.form.setFieldsValue(data);
            this.img = res.data.data.headImageUrl;
            this.id = res.data.data.id;
          }
        });
    },
    putDict() {
      this.form.validateFields((err, values) => {
        if (err) {
          return;
        }
        if (!this.id) {
          const form = values;
          form.headImageUrl = this.img;
          console.log(form, "form");
          const url = "/government-platform-center/humanKeyPoint";
          this.$axios
            .post(url, form, {
              headers: {
                "Content-Type": "application/x-www-form-urlencoded",
              },
            })
            .then((res) => {
              if (res.data.code == 0) {
                this.getList();
                this.reSetForm();
                this.dialogVisible = false;
                message.success("操作成功");
              }
            });
        } else {
          const form = { ...values, id: this.id };
          form.headImageUrl = this.img;
          const url = "/government-platform-center/humanKeyPoint/edit";
          this.$axios
            .post(url, form, {
              headers: {
                "Content-Type": "application/x-www-form-urlencoded",
              },
            })
            .then((res) => {
              if (res.data.code == 0) {
                this.getList();
                this.reSetForm();
                this.dialogVisible = false;
                message.success("操作成功");
              }
            });
        }
      });
    },
    reSetForm() {
      // this.form = { dictName: null, dictType: null, remark: null }
    }, // 处理日期范围变化
    onChange(dates, dateStrings) {
      if (dates) {
        this.queryForm.startTime = dateStrings[0];
        this.queryForm.endTime = dateStrings[1];
      } else {
        this.queryForm.startTime = null;
        this.queryForm.endTime = null;
      }
    },
    getAge(idCard) {
      // 验证身份证号码格式
      if (!/^(\d{15}$)|^\d{17}[\dXx]$/.test(idCard)) {
        return 0;
      }

      let year, month, day;

      // 解析出生年月日
      if (idCard.length === 15) {
        // 15位身份证
        year = 1900 + parseInt(idCard.substr(6, 2), 10);
        month = parseInt(idCard.substr(8, 2), 10) - 1; // 月份从0开始
        day = parseInt(idCard.substr(10, 2), 10);
      } else {
        // 18位身份证
        year = parseInt(idCard.substr(6, 4), 10);
        month = parseInt(idCard.substr(10, 2), 10) - 1;
        day = parseInt(idCard.substr(12, 2), 10);
      }

      // 校验日期有效性
      const birthDate = new Date(year, month, day);
      if (
        birthDate.getFullYear() !== year ||
        birthDate.getMonth() !== month ||
        birthDate.getDate() !== day
      ) {
        return 0;
      }

      // 计算年龄
      const today = new Date();
      let age = today.getFullYear() - birthDate.getFullYear();
      const monthDiff = today.getMonth() - birthDate.getMonth();
      const dayDiff = today.getDate() - birthDate.getDate();

      // 调整未过生日的情况
      if (monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)) {
        age--;
      }

      return age > 0 ? age : 0;
    },
    togglePhoneVisibility(record) {
      this.$set(record, "showPhone", !record.showPhone);
    },
    toggleIdNumberVisibility2(record) {
      this.$set(record, "showIdCardNumber", !record.showIdCardNumber);
    },
  },
};
</script>

<style lang="scss" scoped>
.ant-row {
  border-radius: 5px;

  background: #fff;
  color: #000;
}

v-deep {
  .ant-table-thead > tr > th {
    color: #000;
    font-weight: bold;
  }
  .ant-table-tbody > tr > td {
    color: #000;
  }
  .el-table thead {
    color: black;
    font-weight: bold;
    background: #fafafa;
  }
  .el-table th.el-table__cell {
    background: #fafafa;
  }
}

.ant-col {
  margin: 10px 0;
}

.ant-select {
  width: 60%;
}

.ant-input {
  width: 60%;
}

@media screen and (max-width: 1300px) {
  .el-input {
    width: 70%;
  }

  .el-select {
    width: 70%;
  }

  .app {
    width: calc(100% - 50px);
  }
}

@media screen and (max-width: 1100px) {
  .el-input {
    width: 90%;
  }

  .el-select {
    width: 90%;
  }
}
</style>
